<template>
  <div class="bg-gray-50 min-h-screen p-4 md:p-6">
    <el-card class="mb-6 shadow-sm bg-white rounded-lg">
      <template #header>
        <div class="flex items-center justify-between">
          <h3 class="text-lg font-semibold text-gray-800 flex items-center">
            <i class="fa-solid fa-chart-line mr-2 text-primary"></i>
            销售额趋势分析
          </h3>
          <div class="flex space-x-2">
            <el-select v-model="selectedYear" placeholder="选择年份" size="small">
              <el-option
                v-for="year in yearOptions"
                :key="year"
                :label="`${year}年`"
                :value="year"
              />
            </el-select>
            <el-button size="small" type="primary" @click="refreshData">
              <i class="fa-solid fa-refresh mr-1"></i>刷新
            </el-button>
          </div>
        </div>
      </template>
      <div class="h-[400px]" ref="chartContainer"></div>
    </el-card>

    <el-card class="shadow-sm bg-white rounded-lg">
      <template #header>
        <h3 class="text-lg font-semibold text-gray-800">
          <i class="fa-solid fa-table mr-2 text-primary"></i>
          销售数据明细
        </h3>
      </template>
      <el-table :data="salesData" stripe style="width: 100%">
        <el-table-column prop="month" label="月份" width="120" align="center" />
        <el-table-column prop="sales" label="销售额(万元)" align="right" />
        <el-table-column prop="growthRate" label="环比增长率" align="right">
          <template #default="scope">
            <span :class="scope.row.growthRate >= 0 ? 'text-green-500' : 'text-red-500'">
              {{ scope.row.growthRate >= 0 ? '↑' : '↓' }}
              {{ (scope.row.growthRate * 100).toFixed(2) }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column label="趋势">
          <template #default="scope">
            <el-progress :percentage="scope.row.percentage" :color="progressColor(scope.row.growthRate)" />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'

// 数据状态
const chartContainer = ref(null)
const chartInstance = ref(null)
const selectedYear = ref(new Date().getFullYear())
const yearOptions = ref([2023, 2024, 2025])
const salesData = ref([])

// 生成模拟数据
const generateSalesData = (year) => {
  const data = []
  let lastSales = Math.floor(Math.random() * 50) + 50 // 初始销售额基数
  
  for (let i = 1; i <= 12; i++) {
    // 生成有一定趋势的销售额数据
    const trendFactor = i <= 6 ? 1.05 : 0.98 // 上半年增长，下半年略有下降
    const randomFactor = 0.9 + Math.random() * 0.2 // 随机波动 90%-110%
    const sales = Math.floor(lastSales * trendFactor * randomFactor)
    
    // 计算环比增长率
    const growthRate = i === 1 ? 0 : (sales - lastSales) / lastSales
    
    data.push({
      month: `${i}月`,
      sales,
      growthRate,
      percentage: Math.min(Math.max(sales / 150 * 100, 20), 100) // 进度条百分比
    })
    
    lastSales = sales
  }
  
  return data
}

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return
  
  chartInstance.value = echarts.init(chartContainer.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      },
      formatter: (params) => {
        const param = params[0]
        return `${param.name}<br/>
                <span style="color:${param.color}">●</span> 销售额: ${param.value}万元<br/>
                ${param.data.growthRate >= 0 ? '↑' : '↓'} 
                ${(param.data.growthRate * 100).toFixed(2)}%`
      }
    },
    legend: {
      data: ['销售额(万元)'],
      right: '10%'
    },
    xAxis: {
      type: 'category',
      data: salesData.value.map(item => item.month),
      axisLabel: {
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      axisLabel: {
        formatter: '{value} 万元'
      },
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '销售额(万元)',
        type: 'line',
        data: salesData.value.map(item => ({
          value: item.sales,
          growthRate: item.growthRate
        })),
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#409eff'
        },
        lineStyle: {
          width: 3,
          color: '#409eff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(64, 158, 255, 0.3)'
              },
              {
                offset: 1,
                color: 'rgba(64, 158, 255, 0)'
              }
            ]
          }
        }
      }
    ]
  }
  
  chartInstance.value.setOption(option)
}

// 刷新数据
const refreshData = () => {
  salesData.value = generateSalesData(selectedYear.value)
  if (chartInstance.value) {
    chartInstance.value.setOption({
      xAxis: {
        data: salesData.value.map(item => item.month)
      },
      series: [
        {
          data: salesData.value.map(item => ({
            value: item.sales,
            growthRate: item.growthRate
          }))
        }
      ]
    })
  }
}

// 进度条颜色
const progressColor = (growthRate) => {
  if (growthRate > 0.1) return '#52c41a' // 增长超过10%为绿色
  if (growthRate < -0.1) return '#f5222d' // 下降超过10%为红色
  return '#faad14' // 其他为橙色
}

// 生命周期钩子
onMounted(() => {
  salesData.value = generateSalesData(selectedYear.value)
  nextTick(() => {
    initChart()
  })
})

// 监听年份变化
watch(selectedYear, () => {
  refreshData()
})

// 监听窗口大小变化，调整图表
window.addEventListener('resize', () => {
  if (chartInstance.value) {
    chartInstance.value.resize()
  }
})
</script>

<style scoped>
/* 为图表容器添加过渡效果 */
.chart-container {
  transition: all 0.3s ease;
}

/* 自定义表格样式 */
.el-table .cell {
  padding: 8px 0;
}
</style>    